package com.net;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;

public class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    protected void messageReceived(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
        String req = msg.content().toString(CharsetUtil.UTF_8);
        if ("test0".equals(req)) {
            ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(("messageReceived: 谚语查询结果:" +  CharsetUtil.UTF_8).getBytes(CharsetUtil.UTF_8)), msg.sender()));
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

        System.out.println("exceptionCaught  " );

        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception{
        String req = msg.content().toString(CharsetUtil.UTF_8);


        System.out.println("channelRead0  : "  + req);

        if ("test1".equals(req)) {
            ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(("channelRead0: 谚语查询结果:" +  CharsetUtil.UTF_8).getBytes(CharsetUtil.UTF_8)), msg.sender()));
        }
    }
}
